-- UIEquipTooltip
-- Create by luohj Mar/12/2015
-- 装备悬浮界面

UIEquipTooltip = class("UIEquipTooltip",function()
    return cc.Layer:create();
end);

function UIEquipTooltip.create(classId, artifactType)
    return UIEquipTooltip.new(classId, artifactType);
end

local ARTIFACT_UPGRADED = 2 -- 神器升级后的信息

local MAX_LEVEL = 9;

-- 构造函数
function UIEquipTooltip:ctor(classId, artifactType)
    self:setName("UIEquipTooltip");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/equip/equipOperate.csb");
    self:addChild(node);
    self.node = node;
    local CT = node:getChildByName("CT");

    self.maxLevel = FormulaM.invoke("GET_ARTIFACT_MAX_LEVEL");

    self:setTouches();

    -- 记录装备id
    self.classId = classId;

    -- self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
    if artifactType ~= "operate" then
        self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    end

    self.CT = CT;

    if artifactType ~= nil then
        self.artifactType = artifactType;
    end

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();

    self:registerEventCallback();
end

function UIEquipTooltip:registerEventCallback()
     -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then

            if UIMgr.getCurrentScene().topMenu then
                UIMgr.getCurrentScene().topMenu:setVisible(true);
            end

            EventMgr.removeAll("UIEquipTooltip");

        elseif eventType == "enter" then

        end
    end);

     -- 注册获得焦点的回调
    if self.artifactType == "operate" then
        EventMgr.register("UIEquipTooltip", event.FOCUS_CHANGED, function(para)
            if para["get"] == "UIEquipTooltip" then
               UIMgr.getCurrentScene().topMenu:setVisible(false);
            end

            if para["lose"] == "UIEquipTooltip" then
                UIMgr.getCurrentScene().topMenu:setVisible(true);
            end

        end);
    end
end

-- 设置不吞点击事件，可以时关闭
function UIEquipTooltip:setTouches()
    local bg = findChildByName(self.node, "CT/bg");

    for i = 1, 4 do
        local subBg = findChildByName(bg, "bg" .. i);
        if subBg ~= nil then
            subBg:setSwallowTouches(false);
        end
    end
end

-- 注册点击事件
function UIEquipTooltip:registerTouchEvent()
    -- 注册返回按钮点击事件
    local node = self.node;
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIEquipTooltip");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册背景点击事件
    local bg = findChildByName(node, "bg/bgImg");
    local function onBgClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIEquipTooltip");
        end
    end
    bg:addTouchEventListener(onBgClick);
end

-- 重绘
function UIEquipTooltip:redraw()
    local itemInfo = ItemM.query(self.classId);
    local equipInfo = EquipM.query(self.classId);

    -- 获取不到装备信息？
    if not itemInfo or not equipInfo then
        return;
    end

    -- 设置装备阶位
    local rank = EquipM.getRealRank(self.classId); -- equipInfo["rank"];
    self.rank = rank;

    -- 星级控件
    local starNode = self.CT:getChildByName("star_node");

    local starLayer = createStarLayer(rank, "images/ui/symbol/star_large.png", "right");

    if starLayer then
        starNode:removeAllChildren();
        starNode:addChild(starLayer);
    end

    -- 设置装备名称
    local nameLabel = self.CT:getChildByName("name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    nameLabel:setString(itemInfo["name"]);

    -- 设置装备描述
    local descLabel = self.CT:getChildByName("description");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel:setString(itemInfo["desc"]);

    -- 设置装备效果
    local effectLabel = self.CT:getChildByName("effect");
    local props = EquipM.fetchEquipProp(self.classId);
    local equipEffectTxt = EquipM.getEquipPropDesc(props, self.classId, self.isEquiped);
    TextStyleM.setTextStyle(effectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
    local effectLabel = applyString(effectLabel, equipEffectTxt);

    -- 设置套装显示
    local suitNameLabel   = self.CT:getChildByName("suit_name");
    local suitSubLabel    = self.CT:getChildByName("suit_sub");
    local suitEffectLabel = self.CT:getChildByName("suit_effect");

    local btnEquipSet = self.CT:getChildByName("btn_equip_mount");
    btnEquipSet:setVisible(false);

    local suitId = equipInfo["suit"];
    if suitId and suitId ~= 0 then
        suitNameLabel:setVisible(true);
        suitSubLabel:setVisible(true);
        suitEffectLabel:setVisible(true);

        -- 套装信息
        local suitInfo = SuitM.query(suitId);
        if not suitInfo then
            error("获取不到套装(%d)信息", suitId);
            return;
        end

        local suits = suitInfo["active"];
        local suitCount = #suits;
        local suitActiveCount = 0;
        if suits then
            suitSubLabel:setVisible(true);
            local suitSub = "";
            for i = 1, suitCount do
                local equipId = suits[i];
                local itemName = ItemM.query(equipId, "name");
                local type = EquipM.query(equipId, "type")
                if EquipM.getEquip(type) == equipId then
                    -- 已经装备了，显示激活的颜色
                    suitActiveCount = suitActiveCount + 1;
                    itemName = "[brown]" .. itemName .. "[-]";
                elseif table.indexOf(table.keys(EquipM.queryEquipments(type)), equipId) > 0 then
                    -- 有，但是没装备，显示绿色
                    itemName = "[green]" .. itemName .. "[-]";
                else
                    -- 完全没这件，显示灰色
                    itemName = "[gray]" .. itemName .. "[-]";
                end

                suitSub = suitSub .. itemName;
                if i ~= suitCount then
                    suitSub = suitSub .. "\n";
                end
            end

            TextStyleM.setTextStyle(suitSubLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            suitSubLabel = applyString(suitSubLabel, suitSub);
        end

        -- 设置套装名字
        local suitNameTxt = suitInfo["name"] .. "(" .. suitActiveCount .. "/" .. suitCount .. ")";
        TextStyleM.setTextStyle(suitNameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
        suitNameLabel:setString(suitNameTxt);

        -- 设置套装效果 当套装效果未激活时，效果值显示为“？”；效果集齐时，显示具体属性
        local props = SuitM.calcSuitBaseProp(suitId);
        local suitEffect = EquipM.getEquipPropDesc(props);
        if suitActiveCount == suitCount then
            TextStyleM.setTextStyle(suitEffectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
        else
            TextStyleM.setTextStyle(suitEffectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);
        end
        suitEffectLabel = applyString(suitEffectLabel, suitEffect);
    else
        suitNameLabel:setVisible(false);
        suitSubLabel:setVisible(false);
        suitEffectLabel:setVisible(false);
    end

    local artifactTitleLabel = self.CT:getChildByName("artifact_upgrade");
    local artifacDescLabel = self.CT:getChildByName("artifact_upgrade_prop");

    -- 设置神器强化属性
    if itemInfo.type == ITEM_TYPE_ARTIFACT then
        artifactTitleLabel:setVisible(true);
        artifacDescLabel:setVisible(true);
        local level = ArtifactM.getArtifactLevel(self.classId);

        local rank = FormulaM.invoke("CALC_ARTIFACT_RANK", self.classId);
        local starLayer = createStarLayer(rank, "images/ui/symbol/star_large.png", "right");

        if starLayer then
            starNode:removeAllChildren();
            starNode:addChild(starLayer);
        end

        -- 未获得神器level为-1
        if level == -1 then
            level = 0;
        end

        if self.artifactType == ARTIFACT_UPGRADED then
            level = level + 1;
        end

        TextStyleM.setTextStyle(artifactTitleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
        artifactTitleLabel:setString(string.format(getLocStr("artifact_upgrade_title"), level, self.maxLevel));

        local desc = ArtifactM.getUpgradePropDesc(self.classId, level);
        TextStyleM.setTextStyle(artifacDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);


        if self.artifactType == "operate" then
            if ItemM.getAmount(ME.user, self.classId) < 1 then
                -- 没有神器神，显示合成
                local scrapName = ItemM.query(self.classId + 200, "name");

                local str = getLocStr("compound_artifact");
                local amount;
                local costTable = ArtifactM.getCompoundCost(self.classId);
                for _, cost in pairs(costTable) do
                    if cost[1] == 1 then
                        amount = cost[3]
                        break;
                    end
                end

                local scrapAmount = ItemM.getAmount(ME.user, self.classId + 200);
                local str1 = "%d/%d";
                if amount > scrapAmount then
                    str = getLocStr("compound_artifact2");
                    btnEquipSet:setVisible(true);
                    -- btnEquipSet:setEnabled(false);
                    -- btnEquipSet:setBright(false);
                end
                str1 = string.format(str1, scrapAmount, amount);
                str = string.format(str, scrapName, str1);

                desc = desc .. "\n" .. str;
                btnEquipSet:setVisible(true);
                -- 注册神器合成
                local function onEquipClick(sender, eventType)
                    if eventType == ccui.TouchEventType.ended then
                        -- 显示神器合成
                        UIMgr.getCurrentScene():removeFormByName("UIArtifactCompound");
                        local uiCompound = UIArtifactCompound.create(self.classId);
                        UIMgr.getCurrentScene():addForm(uiCompound);
                        UIMgr.getCurrentScene():removeFormByName("UIEquipTooltip");
                        AudioM.playFx("ui_open1");
                    end
                end
                btnEquipSet:addTouchEventListener(onEquipClick);
                TextStyleM.setTextStyle(btnEquipSet, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
                btnEquipSet:setTitleText(getLocStr("btn_text_compound"));
            else
                -- 显示强化
                local scrapName = ItemM.query(self.classId + 200, "name");

                local str = getLocStr("upgrade_artifact");
                local amount = 0;

                -- 获得神器当前的等级
                local artifactLevel = ArtifactM.getArtifactLevel(self.classId);

                -- 神器等级
                local costTable = {};
                if artifactLevel < self.maxLevel then
                    costTable= ArtifactM.getUpgradeCost(self.classId);
                end


                local scrapAmount = ItemM.getAmount(ME.user, self.classId + 200);
                local str1 = "%d/%d";

                local canUpgrade = ArtifactM.canUpgrade(self.classId);
                -- 不足强化消耗或合成数大于2，说明需要遗物，需要显示红色
                if canUpgrade ~= true then
                --     str = getLocStr("upgrade_artifact2");
                     btnEquipSet:setVisible(true);
                     -- btnEquipSet:setEnabled(false);
                     -- btnEquipSet:setBright(false);
                end

                if artifactLevel == self.maxLevel then
                    str1 = string.format("%d/%s", scrapAmount, "-");
                    btnEquipSet:setVisible(true);
                    btnEquipSet:setEnabled(false);
                    btnEquipSet:setBright(false);
                    str1 = string.format(str1, scrapAmount, amount);
                    str = string.format(str, scrapName, str1);

                    desc = desc .. str;
                else
                    if #costTable == 2 then
                        for _, cost in pairs(costTable) do
                            if cost[1] == 1 then
                                amount = cost[3];
                                break;
                            end
                        end
                        str1 = string.format(str1, scrapAmount, amount);
                        str = string.format(str, scrapName, str1);
                    elseif # costTable == 3 then
                        -- 显示需求
                        local str1 = getLocStr("upgrade_artifact_cost");
                        local needRelicAmount = 0;
                        local needScrapAmount = 0;
                        local scrapAmount = 0;
                        local relicName;
                        local scrapName;
                        local str2 = "[green]%d[-]";
                        for _, cost in pairs(costTable) do
                            if cost[1] == 1 then
                                if ArtifactM.isArtifactScrap(cost[2]) then
                                    needScrapAmount = cost[3];
                                    scrapAmount = ItemM.getAmount(ME.user, cost[2]);
                                    scrapName = ItemM.query(cost[2], "name");
                                else
                                    needRelicAmount = cost[3];
                                    relicName = ItemM.query(cost[2], "name");
                                    local relicAmount = ItemM.getAmount(ME.user, cost[2]);
                                    if relicAmount <  needRelicAmount then
                                        str2 = "[red]%d[-]";
                                    end
                                    str2 = string.format(str2, relicAmount);
                                end

                            end
                        end

                        str = string.format(str1, scrapName, scrapAmount, needScrapAmount + needRelicAmount, relicName, str2, needRelicAmount);
                    end
                    desc = desc .."\n".. str;
                end

                btnEquipSet:setVisible(true);
                local function onEquipClick(sender, eventType)
                    if eventType == ccui.TouchEventType.ended then
                        -- 显示神器合成

                        UIMgr.getCurrentScene():removeFormByName("UIArtifactUpgrade");
                        local uiCompound = UIArtifactUpgrade.create(self.classId);
                        UIMgr.getCurrentScene():addForm(uiCompound);
                        UIMgr.getCurrentScene():removeFormByName("UIEquipTooltip");
                        AudioM.playFx("ui_open1");
                    end
                end
                btnEquipSet:addTouchEventListener(onEquipClick);
                TextStyleM.setTextStyle(btnEquipSet, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
                btnEquipSet:setTitleText(getLocStr("btn_text_intensify"));
            end
        end

        artifacDescLabel = applyString(artifacDescLabel, desc);
    elseif HolyItemsM.isHolyItems(self.classId) then
        -- 如果是圣器，显示圣器的特殊属性
        artifactTitleLabel:setVisible(true);
        artifacDescLabel:setVisible(true);
        local level = HolyItemsM.getExtraLevel(self.classId);
        local maxLevel = HolyItemsM.query(self.classId, "max_extra_level");
        TextStyleM.setTextStyle(artifactTitleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
        artifactTitleLabel:setString(string.format(getLocStr("holy_items_upgrade_title"), level, maxLevel));

        -- 获取圣器的特殊属性描述
        local desc = HolyItemsM.getExtraPropDesc(self.classId);
        if level > 0 then
            TextStyleM.setTextStyle(artifacDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
        else
            TextStyleM.setTextStyle(artifacDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);
        end
        artifacDescLabel = applyString(artifacDescLabel, desc);
    else
        artifactTitleLabel:setVisible(false);
        artifacDescLabel:setVisible(false);
    end

    -- 可能是强化
    local operateLabel = findChildByName(self.node, "CT/artifact_label");
    operateLabel:setVisible(false);
    TextStyleM.setTextStyle(operateLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);

    -- 重绘按钮
    self:redrawButtons();

    -- 自适应所有组件
    local btnEquipSet = self.CT:getChildByName("btn_equip_mount");
    local bg = findChildByName(self.node, "CT/bg");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { nameLabel, descLabel, effectLabel, suitNameLabel, suitSubLabel,
            suitEffectLabel, artifactTitleLabel, artifacDescLabel, btnEquipSet});

    -- 星星与装备名称在同一行
    starNode:setPositionY(nameLabel:getPositionY());
end

-- 重绘按钮
function UIEquipTooltip:redrawButtons()
    -- 重绘返回按钮
    local btnBack = findChildByName(self.node, "BT/btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 隐藏分解按钮、装备按钮
    local btnResolve = findChildByName(self.node, "BT/btn_resolve");
    btnResolve:setVisible(false);
end

-- 适配
function UIEquipTooltip:resize()
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end


